package com.ljw.vendingmachine;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ljw.vendingmachine.adapter.ExamplePagerAdapter;
import com.ljw.vendingmachine.base.BaseActivity;
import com.ljw.vendingmachine.bean.Goods;
import com.ljw.vendingmachine.bean.GoodsType;
import com.ljw.vendingmachine.bean.MessageEvent;
import com.ljw.vendingmachine.utils.Constant;
import com.ljw.vendingmachine.utils.GsonUtil;
import com.ljw.vendingmachine.utils.LayoutUtil;
import com.ljw.vendingmachine.utils.SPUtils;
import com.ljw.vendingmachine.widget.MoveImageView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import static com.chad.library.adapter.base.BaseQuickAdapter.SCALEIN;
import static net.lucode.hackware.magicindicator.ScrollState.SCROLL_STATE_SETTLING;

public class MoreGoodsActivity extends BaseActivity {

    //商品列表
    @BindView(R.id.rv_goods)
    RecyclerView rv_goods;
    //无用布局--配合指示器不能删除
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    //指示器
    @BindView(R.id.magic_indicator)
    MagicIndicator magic_indicator;
    //根布局
    @BindView(R.id.more_goods_RootLayout)
    RelativeLayout more_goods_RootLayout;
    //购物车按钮
    @BindView(R.id.tv_toCar)
    TextView tv_toCar;
    //总数量
    @BindView(R.id.tv_goodsnumber)
    TextView tv_goodsnumber;
    //总金额
    @BindView(R.id.tv_sum_price)
    TextView tv_sum_price;
    @BindView(R.id.tv_toMain)
    TextView tv_toMain;
    private BaseQuickAdapter<Goods, BaseViewHolder> goods_list_adapter;
    private PopupWindow goodscar;
    private View inflate;
    private RecyclerView car_list;
    private BaseQuickAdapter<Goods, BaseViewHolder> car_listAdapter;
    private MoreGoodsAnimator moreGoodsAnimator;
    private TextView pop_tv_goodsnumber;
    private TextView pop_tv_sum_price;
    private Timer timer;
    int startTime = 100;

    @Override
    public int setContentView() {
        return R.layout.activity_more_goods;
    }

    @Override
    public void afterSetContentView() {
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化界面空间
     */
    @Override
    public void initView() {

        moreGoodsAnimator = new MoreGoodsAnimator(more_goods_RootLayout, tv_goodsnumber, tv_sum_price);
        List<GoodsType> types = (List<GoodsType>) getIntent().getSerializableExtra("types");
        initMagicIndicator(types);

        inflate = LayoutInflater.from(this).inflate(R.layout.goods_car_layout, null, false);
        setPopOnClick(inflate);
        goodscar = LayoutUtil.createPopupWindow(inflate);
        rv_goods.setLayoutManager(new GridLayoutManager(this, 3));
        goods_list_adapter = new BaseQuickAdapter<Goods, BaseViewHolder>(R.layout.goods_item, null) {
            @Override
            protected void convert(BaseViewHolder helper, Goods item) {
                helper.setText(R.id.goods_name, item.getGoodsName());
                helper.setText(R.id.goods_price, Html.fromHtml(String.format(getString(R.string.goods_price), item.getGoodsPrice())));
                helper.setText(R.id.tv_stockNum, "库存:" + item.getStockNum());
                Glide.with(MoreGoodsActivity.this)
                        .load(item.getPicUrl())
                        .into((ImageView) helper.getView(R.id.goods_img));
                helper.addOnClickListener(R.id.btn_addtocar);
            }
        };
        goods_list_adapter.openLoadAnimation(SCALEIN);
        goods_list_adapter.bindToRecyclerView(rv_goods);
        //    rv_goods.setAdapter(goods_list_adapter);

        goods_list_adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Goods item = (Goods) adapter.getItem(position);
                addTOCar(item, view);
//                int num = item.getStockNum();
//                if (num !=0){
//                    //如果购物车已经有这个物品购物车 数量加1
//                if (MainActivity.goodsMap.contains(item)){
//                    Goods goods1 = MainActivity.goodsMap.get(MainActivity.goodsMap.indexOf(item));
//                    int stockNum = goods1.getStockNum() + 1;
//                    boolean b = stockNum > num;
//
//                    if (b){
//                        //如果超出库存就提示
//                       // Toast.makeText("")
//                    }else{
//                        //没有就加1
//                        goods1.setStockNum(stockNum);
//                    }
//
//                }else{
//                    Goods clone = (Goods) item.clone();
//                    clone.setStockNum(1);
//                    MainActivity.goodsMap.add(clone);
//                }
//                }else{
//                    //提示库存为零
//                }
                //  goodscar.showAtLocation(rv_goods.getRootView(), Gravity.BOTTOM,0,0);
            }
        });

        //如果分类列表有数据就
        if (types != null && types.size() > 0) {
            getTypeData(types.get(0).getId());
        }


    }

    private void getTypeData(int type) {
        MessageEvent mes = new MessageEvent();
        mes.setCode(Constant.SEND_CMD);
        mes.setData(String.format(Constant.COMD_GET_MORE_GOODS, type));
        EventBus.getDefault().post(mes);
    }

    public void addTOCar(Goods goods, View view) {

        List<Goods> data = car_listAdapter.getData();
        if (0 == goods.getStockNum()) {
            Toast.makeText(this, "货架此商品数量为0,无法购买！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (data.contains(goods)) {
            int index = data.indexOf(goods);
            if (Constant.NUMBER == 0) {
                Goods goods1 = data.get(index);
                int stockNum = goods1.getStockNum();
                int stockNumadd1 = stockNum + 1;

                if (goods.getStockNum() < stockNumadd1) {

                    goods1.setStockNum(stockNum);
                    Toast.makeText(this, "此商品货架数量" + goods.getStockNum(), Toast.LENGTH_SHORT).show();

                    return;
                } else {
                    goods1.setStockNum(stockNumadd1);

                }
                car_listAdapter.notifyItemChanged(index);
                initAnimation(view);
            } else {
                Goods goods1 = data.get(index);
                int stockNum = goods1.getStockNum();
                int stockNumadd1 = stockNum + 1;

                if (stockNumadd1 > Constant.NUMBER || goods.getStockNum() < stockNumadd1) {

                    goods1.setStockNum(stockNum);
                    Toast.makeText(this, "超出限制！", Toast.LENGTH_SHORT).show();

                    return;
                } else {
                    goods1.setStockNum(stockNumadd1);

                }
                car_listAdapter.notifyItemChanged(index);
                initAnimation(view);
                // Toast.makeText(this,"每个商品只能购买1个哦！",Toast.LENGTH_SHORT).show();
            }

        } else {
            Goods bean = (Goods) goods.clone();
            bean.setStockNum(1);
            car_listAdapter.addData(bean);
            initAnimation(view);
        }


    }

    /**
     * @param event 刷新总数 与总价
     */
    @Subscribe
    public void flushTotalAndPrice(MessageEvent event) {
        if (Constant.EVENTBUS_CODE_FLUSH_TOTAL_SUMPRICE == event.getCode()) {


            int total = 0;
            double sumPrice = 0;
            for (Goods datum : car_listAdapter.getData()) {
                int stockNum = datum.getStockNum();
                total = total + stockNum;
                double v = Double.parseDouble(datum.getGoodsPrice());
                sumPrice = sumPrice + (stockNum * v);
            }
            if (total != 0) {
                String total_str = "购物车(" + total + ")";

                tv_goodsnumber.setText(total_str);
                pop_tv_goodsnumber.setText(total_str);
            } else {
                String car_str = "购物车";
                tv_goodsnumber.setText(car_str);
                pop_tv_goodsnumber.setText(car_str);
            }

            String sumprice_str = "￥:" + sumPrice;
            tv_sum_price.setText(sumprice_str);
            pop_tv_sum_price.setText(sumprice_str);
        }
    }

    /**
     * @param pop 购物车弹窗
     */
    public void setPopOnClick(View pop) {
        View disMiss = pop.findViewById(R.id.tv_PopDiss);
        pop_tv_goodsnumber = (TextView) pop.findViewById(R.id.tv_goodsnumber);
        pop_tv_sum_price = (TextView) pop.findViewById(R.id.tv_sum_price);
        disMiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodscar.dismiss();
            }
        });
        View tv_topay = pop.findViewById(R.id.tv_topay);
        tv_topay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.goodsMap.size() == 0) {
                    Toast.makeText(MoreGoodsActivity.this, "请先将要购买的商品加入购物车！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(MoreGoodsActivity.this, PayActivity.class);
                //  intent.putExtra("goodslist", (Serializable) car_listAdapter.getData());
                startActivity(intent);
            }
        });
        View clear = pop.findViewById(R.id.tv_clearcar);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                car_listAdapter.getData().clear();
                car_listAdapter.notifyDataSetChanged();
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setCode(Constant.EVENTBUS_CODE_FLUSH_TOTAL_SUMPRICE);
                messageEvent.setMessage("刷新总数和总价");
                EventBus.getDefault().post(messageEvent);
            }
        });
        car_list = (RecyclerView) pop.findViewById(R.id.RecyclerView_goods);
        car_list.setLayoutManager(new LinearLayoutManager(this));
        HorizontalDividerItemDecoration build = new HorizontalDividerItemDecoration.Builder(this)
                .margin(R.dimen.x20, R.dimen.x20)
                .color(R.color.color_F0F0F0)
                .build();
        car_list.addItemDecoration(build);
        car_listAdapter = new BaseQuickAdapter<Goods, BaseViewHolder>(R.layout.goodscar_item, MainActivity.goodsMap) {
            @Override
            protected void convert(BaseViewHolder helper, Goods item) {
                double goodsPrice = Double.parseDouble(item.getGoodsPrice());
                int stockNum = item.getStockNum();
                helper.setText(R.id.tv_goods_name, item.getGoodsName())
                        .setText(R.id.tv_goods_price, String.valueOf(goodsPrice))
                        .setText(R.id.tv_goods_number, String.valueOf(stockNum))
                        .setText(R.id.tv_goods_sum, String.valueOf(goodsPrice * stockNum));

                helper.addOnClickListener(R.id.tv_delGoods);
            }
        };
        car_listAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_delGoods) {
                    adapter.remove(position);
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setCode(Constant.EVENTBUS_CODE_FLUSH_TOTAL_SUMPRICE);
                    messageEvent.setMessage("刷新总数和总价");
                    EventBus.getDefault().post(messageEvent);
                }

            }
        });
        car_list.setAdapter(car_listAdapter);
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
//        goods_list_adapter.addData("可乐");
//        goods_list_adapter.addData("汽水");
//        goods_list_adapter.addData("雪碧");
//        goods_list_adapter.addData("冰红茶");
//        goods_list_adapter.addData("壮阳水");
//        goods_list_adapter.addData("忘情水");
//        goods_list_adapter.addData("还魂草");
//        goods_list_adapter.addData("破境丹");
//        goods_list_adapter.addData("鹤顶红");
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setCode(Constant.EVENTBUS_CODE_FLUSH_TOTAL_SUMPRICE);
        messageEvent.setMessage("刷新总数和总价");
        EventBus.getDefault().post(messageEvent);


    }


    /**
     * 弹出购物车列表
     */
    @OnClick(R.id.tv_toCar)
    public void toCar() {
        goodscar.showAtLocation(rv_goods.getRootView(), Gravity.BOTTOM, 0, 0);
//        Intent intent=new Intent(this,PayActivity.class);
//        startActivity(intent);
    }

    /**
     * @param onClickV 动画
     */
    public void initAnimation(View onClickV) {
        //1.分别获取被点击View、父布局、购物车在屏幕上的坐标xy。
        int[] childCoordinate = new int[2];
        int[] parentCoordinate = new int[2];
        int[] shopCoordinate = new int[2];

        onClickV.getLocationInWindow(childCoordinate);
        more_goods_RootLayout.getLocationInWindow(parentCoordinate);
        tv_goodsnumber.getLocationInWindow(shopCoordinate);
        //2.自定义ImageView 继承ImageView
        MoveImageView img = new MoveImageView(this);
        img.setImageResource(R.drawable.ic_goodscar);
        //3.设置img在父布局中的坐标位置
        img.setX(childCoordinate[0] - parentCoordinate[0]);
        img.setY(childCoordinate[1] - parentCoordinate[1]);
        //4.父布局添加该Img
        more_goods_RootLayout.addView(img);
        //5.利用 二次贝塞尔曲线 需首先计算出 MoveImageView的2个数据点和一个控制点
        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();
        //开始的数据点坐标就是 addV的坐标
        startP.x = childCoordinate[0] - parentCoordinate[0];
        startP.y = childCoordinate[1] - parentCoordinate[1];
        //结束的数据点坐标就是 shopImg的坐标
        endP.x = shopCoordinate[0] - parentCoordinate[0];
        endP.y = shopCoordinate[1] - parentCoordinate[1];
        //控制点坐标 x等于 购物车x；y等于 addV的y
        controlP.x = endP.x;
        controlP.y = startP.y;

        //启动属性动画
        ObjectAnimator animator = ObjectAnimator.ofObject(img, "mPointF",
                new PointFTypeEvaluator(controlP), startP, endP);
        animator.setDuration(1000);
        animator.addListener(moreGoodsAnimator);
        animator.start();
    }

    /**
     * 结束页面跳转到首页
     */
    @OnClick(R.id.tv_toMain)
    public void toMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (goodscar!=null)goodscar.dismiss();
        EventBus.getDefault().unregister(this);
        timer.cancel();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveData(MessageEvent event) {
        if (Constant.EVENTBUS_CODE_MORE_GOODS_LIST == event.getCode()) {
            if (goods_list_adapter != null) {
                JSONArray data = (JSONArray) event.getData();
                //商品列表

                List<Goods> list = GsonUtil.GsonToList(data.toString(), Goods[].class);
                goods_list_adapter.replaceData(list);


            }
        }
        if (Constant.RE_CONNECT == event.getCode()) {
            if ((boolean) event.getData()) {
                dialog.show();
            } else {
                dialog.dismiss();
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        timer = new Timer();
        startTime = 100;
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                startTime--;
                if (startTime == 0) {
                    toMain();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (tv_toMain != null)
                                tv_toMain.setText("首页(" + startTime + ")");
                        }
                    });
                }
            }
        }, 1000, 1000);
    }

    @Override
    protected void onPause() {

        super.onPause();
        timer.cancel();
    }


    private void initMagicIndicator(final List<GoodsType> mDataList) {
        mViewPager.setAdapter(new ExamplePagerAdapter(mDataList));
        magic_indicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(Color.parseColor("#474456"));
                simplePagerTitleView.setSelectedColor(Color.parseColor("#F8B551"));
                simplePagerTitleView.setText(mDataList.get(index).getType());
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getTypeData(mDataList.get(index).getId());
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(Color.parseColor("#F8B551"));
                return linePagerIndicator;
            }
        });
        magic_indicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magic_indicator, mViewPager);
    }

}
